package com.jsyl.lwbk.quartz.service.impl;

import com.jsyl.lwbk.business.constant.NewChildProgramConstant;
import com.jsyl.lwbk.business.domain.Child;
import com.jsyl.lwbk.business.domain.ChildCenter;
import com.jsyl.lwbk.business.domain.EvaluateRecord;
import com.jsyl.lwbk.business.domain.EvaluateReport;
import com.jsyl.lwbk.business.domain.education.*;
import com.jsyl.lwbk.business.mapper.education.*;
import com.jsyl.lwbk.business.dto.ChildReportDTO;
import com.jsyl.lwbk.business.dto.ReportScoreDTO;
import com.jsyl.lwbk.business.dto.education.ChildTrainingProgramDTO;
import com.jsyl.lwbk.business.dto.education.QmsChildrenDTO;
import com.jsyl.lwbk.business.dto.education.QmsCourseDTO;
import com.jsyl.lwbk.business.dto.education.TrainingProgramListDTO;
import com.jsyl.lwbk.business.service.IChildRecordService;
import com.jsyl.lwbk.business.service.IChildService;
import com.jsyl.lwbk.business.service.IEvaluateReportService;
import com.jsyl.lwbk.business.service.education.IChildCourseService;
import com.jsyl.lwbk.business.service.education.IChildTrainingProgramService;
import com.jsyl.lwbk.business.service.education.IQuestionReporttypeService;
import com.jsyl.lwbk.business.service.education.ITrainingProgramService;
import com.jsyl.lwbk.business.vo.education.TrainingScoreCountVO;
import com.jsyl.lwbk.common.utils.DateUtils;
import com.jsyl.lwbk.common.utils.StringUtils;
import com.jsyl.lwbk.quartz.service.IJobService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class JobServiceImpl implements IJobService {

    private static final Logger log = LoggerFactory.getLogger(JobServiceImpl.class);

    @Autowired
    private IChildCourseService iChildCourseService;

    @Autowired
    private IEvaluateReportService evaluateReportService;

    @Autowired
    private IQuestionReporttypeService questionReporttypeService;

    @Autowired
    private IChildRecordService evalueRecordService;

    @Autowired
    private ITrainingProgramService trainingProgramService;

    @Autowired
    private IChildTrainingProgramService childTrainingProgramService;

    @Autowired
    private ChildTrainingProgramMapper childTrainingProgramMapper;

    @Autowired
    private ChildCourseMapper childCourseMapper;

    @Autowired
    private CourseChildMapper courseChildMapper;

    @Autowired
    private OrganizationScheduleDetailMapper organizationScheduleDetailMapper;

    @Autowired
    private OrganizationScheduleDetailChildMapper organizationScheduleDetailChildMapper;

    @Autowired
    private IChildService iChildService;

    @Autowired
    private TrainingProgramChildRecordMapper trainingProgramChildRecordMapper;
    @Autowired
    private ChildMonthPlanMapper childMonthPlanMapper;

    private Integer programCount = 2;


    @Override
    public void testSchedule() {
        log.error("testSchedule");
    }


    @Override
    public void updateConfirm() {
        log.error("定时任务：更新项目确认状态");
        Date nowDate = DateUtils.getNowDate();
        int day = DateUtils.differentDaysByMillisecond(nowDate, DateUtils.getMonthLastDay());
        if (day != 0) {
            log.error("不是当月最后一天");
            return;
        }
        ChildCourseExample example = new ChildCourseExample();
        example.createCriteria().andDayDateBetween(DateUtils.getMonthBegin(DateUtils.getStrTime(DateUtils.getNextMonth())), DateUtils.getMonthEnd(DateUtils.getStrTime(DateUtils.getNextMonth())));
        List<ChildCourse> childCourses = childCourseMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(childCourses)) {
            for (ChildCourse childCourse : childCourses) {
                CourseChildExample courseChildExample = new CourseChildExample();
                courseChildExample.createCriteria().andCourseIdEqualTo(childCourse.getId());
                List<CourseChild> courseChildList = courseChildMapper.selectByExample(courseChildExample);
                if (!CollectionUtils.isEmpty(courseChildList)) {
                    for (CourseChild courseChild : courseChildList) {
                        if (courseChild.getConfirm() == null || courseChild.getConfirm() != 1) {
                            courseChild.setConfirm(1);
                            courseChild.setLastConfirmTime(new Date());
                            courseChildMapper.updateByExample(courseChild, courseChildExample);
                        }
                    }
                }
            }
        }

    }

    @Override
    public void dealLastMonthScore() {
        log.info("定时任务：月末倒数第4天计算本月需巩固项目");
        Date nowDate = DateUtils.getNowDate();
        int day = DateUtils.differentDaysByMillisecond(nowDate, DateUtils.getMonthLastDay());
        //4天内生成,3天内开放编辑
        if (day != 4) {
            log.error("未在月末倒数第4天");
            return;
        }
        List<String> updateList = new ArrayList<>();
        //获取本月有项目得学生
        List<TrainingProgram> list = trainingProgramService.findTrainingProgramList(DateUtils.getCurrentMonth());
        if (org.apache.commons.collections.CollectionUtils.isEmpty(list)) {
            return;
        }
        for (TrainingProgram t : list) {
            //本月项目需巩固次数最多的月小结成绩本项目为需巩固：0-已稳定，1-已达成，2-需巩固，3-未达成
            if (t.getTrainingLevel() == null) {
                updateList.add(t.getId() + "," + "3");
                continue;
            }
            int count0 = 0, count1 = 0, count2 = 0, count3 = 0;
            String[] temp = t.getTrainingLevel().split(",");
            for (String s : temp) {
                if (s.equals("0")) {
                    count0++;
                }
                if (s.equals("1")) {
                    count1++;
                }
                if (s.equals("2")) {
                    count2++;
                }
                if (s.equals("3")) {
                    count3++;
                }
            }
            if (count2 >= count0 && count2 >= count1 && count2 >= count3) {
                updateList.add(t.getId() + ",2");
            }
        }
        String sql = "update t_child_training_program set training_level= CASE id";
        String ids = "";
        for (String s : updateList) {
            if (ids == "") {
                ids = s.split(",")[0];
            } else {
                ids = ids + "," + s.split(",")[0];
            }
            sql += " WHEN " + s.split(",")[0] + " THEN " + s.split(",")[1] + "";
        }
        sql += " END where id in(" + ids + ")";
        if (updateList.size() > 0) {
            this.trainingProgramService.updateTrainingLevel(sql);
            log.info(sql);
        }
    }

    @Override
    public void generateMonthResult() {
        log.info("定时任务：生成月度小结");
        //获取上月有上课的学生
        List<ChildCenter> list = this.trainingProgramChildRecordMapper.getChildList(DateUtils.getLastMonth());
        for (ChildCenter c : list) {
            ChildReport childReport = new ChildReport();
            childReport.setChildId(c.getChildId());
            childReport.setTrainingProgramNumber(DateUtils.getLastMonth());
            childReport.setReportType(2);
            ChildReport local = this.childMonthPlanMapper.getChildMonthPlan(childReport);
            if (null == local) {
                childReport.setTrainingProgramNumber(DateUtils.getLastMonth());
                childReport.setCenterId(c.getCenterIds());
                childReport.setReportType(2);
                childReport.setStatus(0);
                childReport.setCreateBy("systemJob");
                childReport.setCreateTime(DateUtils.getNowDate());
                childReport.setUpdateBy("systemJob");
                childReport.setUpdateTime(DateUtils.getNowDate());
                this.childMonthPlanMapper.insert(childReport);
            }
        }
    }

    public static void main(String[] args) {
        Date nowDate = DateUtils.getNowDate();
        int day = DateUtils.differentDaysByMillisecond(nowDate, DateUtils.getMonthLastDay());
        String a= DateUtils.getMonthBegin(DateUtils.getStrTime(DateUtils.getNextMonth()));
        System.out.println(a);
    }

    @Override
    @Transactional
    public void generateChildTraningProgram() {
        log.error("定时任务：生成项目");
        //无论什么情况都从最近的一份测评记录里生成报告
        Date nowDate = DateUtils.getNowDate();
        //当月未生成优先生成
        //从课程表里面取当月有课的小孩
//        List<CourseChild> currentChildList = iChildCourseService.listCurrentmonthCourseChild();
        List<CourseChild> currentChildList = iChildCourseService.listGenPlanChild();
        if (!CollectionUtils.isEmpty(currentChildList)) {
            for (CourseChild courseChild : currentChildList) {
                //查看是否已经生成过项目
                ChildTrainingProgramDTO childTrainingProgramDTO = new ChildTrainingProgramDTO();
                childTrainingProgramDTO.setChildId(courseChild.getChildId());
                childTrainingProgramDTO.setTrainingProgramNumber(DateUtils.getCurrentMonth());
                childTrainingProgramDTO.setTrainingType(3);
                List<ChildTrainingProgram> childTrainingPrograms = childTrainingProgramService.list(childTrainingProgramDTO);
                childTrainingProgramDTO.setProjectType(courseChild.getProjectType());
                childTrainingProgramDTO.setCenterId(courseChild.getCenterId());
                //查看是否已确认新生标准计划
//                int newProgramCount = this.childTrainingProgramService.countNewProgram(courseChild.getChildId(),DateUtils.getCurrentMonth());
                if (CollectionUtils.isEmpty(childTrainingPrograms)) {
                    //查看小孩90天内是否有测评
                    ChildReportDTO childReportDTO = new ChildReportDTO();
                    childReportDTO.setChildId(courseChild.getChildId());
                    EvaluateReport evaluateReport = evaluateReportService.getLatestChildReport(childReportDTO);
                    //查看小孩90天内是否有上过课（有无成绩记录）
                    Integer recordCount = trainingProgramChildRecordMapper.selectRecordCount(courseChild.getChildId(),90);
                    if (recordCount > 0 ||(evaluateReport != null && DateUtils.differentDaysByMillisecond(evaluateReport.getUpdateTime(), DateUtils.getNowDate()) <= 90)) {
                        generateByEvaluate(courseChild.getChildId(), courseChild.getCenterId(), evaluateReport.getEvaluateNumber(), DateUtils.getCurrentMonth());
                    } else {
                        //没测评则按晋级生成训练项目
                        //查看是否已经生成过项目
                        ChildTrainingProgramDTO dto = new ChildTrainingProgramDTO();
//                        dto.setCenterId(courseChild.getCenterId());
                        dto.setChildId(courseChild.getChildId());
                        dto.setTrainingProgramNumber(DateUtils.getCurrentMonth());
                        dto.setEqTrainingType(3);
                        childTrainingPrograms = childTrainingProgramService.list(dto);
                        if (CollectionUtils.isEmpty(childTrainingPrograms)) {
                            //生成新生标准计划
//                            if (childTrainingProgramDTO.getProjectType()!=null && childTrainingProgramDTO.getProjectType() == 1) {
                                childTrainingProgramDTO.setProjectType(1);
                                dealProgram(childTrainingProgramDTO, NewChildProgramConstant.sportOne, 3);
                                dealProgram(childTrainingProgramDTO, NewChildProgramConstant.sportTwo, 4);
                                dealProgram(childTrainingProgramDTO, NewChildProgramConstant.sportThree, 5);
//                            }
//                            if (childTrainingProgramDTO.getProjectType()!=null && childTrainingProgramDTO.getProjectType() == 2) {
                                childTrainingProgramDTO.setProjectType(2);
                                dealProgram(childTrainingProgramDTO, NewChildProgramConstant.knowledgeOne, 3);
                                dealProgram(childTrainingProgramDTO, NewChildProgramConstant.knowledgeTwo, 4);
                                dealProgram(childTrainingProgramDTO, NewChildProgramConstant.knowledgeThree, 5);
//                            }
//                            if (childTrainingProgramDTO.getProjectType()!=null && childTrainingProgramDTO.getProjectType() == 3) {
                                childTrainingProgramDTO.setProjectType(3);
                                dealProgram(childTrainingProgramDTO, NewChildProgramConstant.languageOne, 3);
                                dealProgram(childTrainingProgramDTO, NewChildProgramConstant.languageTwo, 4);
                                dealProgram(childTrainingProgramDTO, NewChildProgramConstant.languageThree, 5);
//                            }
                        }

                        log.info("没有测评记录");
                    }
                }
            }
        }

        int day = DateUtils.differentDaysByMillisecond(nowDate, DateUtils.getMonthLastDay());
        //4天内生成,3天内开放编辑
        if (day < 0 || day > 3) {
            log.error("未在4天内");
            return;
        }
        //从课程表里面取下个月有课的小孩
        List<CourseChild> childList = iChildCourseService.listNextmonthCourseChild();
        if (CollectionUtils.isEmpty(childList)) {
            return;
        }
        for (CourseChild courseChild : childList) {
            //查看是否已经生成过项目
            ChildTrainingProgramDTO childTrainingProgramDTO = new ChildTrainingProgramDTO();
            childTrainingProgramDTO.setChildId(courseChild.getChildId());
            childTrainingProgramDTO.setTrainingProgramNumber(DateUtils.getNextMonth());
            List<ChildTrainingProgram> childTrainingPrograms = childTrainingProgramService.list(childTrainingProgramDTO);
            childTrainingProgramDTO.setProjectType(courseChild.getProjectType());
            childTrainingProgramDTO.setCenterId(courseChild.getCenterId());
            //查看是否已确认新生标准计划
            int newProgramCount = this.childTrainingProgramService.countNewProgram(courseChild.getChildId(), DateUtils.getNextMonth(), courseChild.getProjectType());
            if (CollectionUtils.isEmpty(childTrainingPrograms) && newProgramCount <= 0) {
                //查看小孩当月是否有测评
                ChildReportDTO childReportDTO = new ChildReportDTO();
                childReportDTO.setChildId(courseChild.getChildId());
//                childReportDTO.setBeginTime(DateUtils.getMonthBegin(new Date()));
//                childReportDTO.setEndTime(DateUtils.getMonthEnd(new Date()));
                EvaluateReport evaluateReport = evaluateReportService.getLatestChildReport(childReportDTO);
                if (evaluateReport != null) {
                    //当月有新测评按测评出，没有按上月结果出
//                    childReportDTO.setBeginTime(DateUtils.getMonthBegin(new Date()));
//                    childReportDTO.setEndTime(DateUtils.getMonthEnd(new Date()));
//                    evaluateReport = evaluateReportService.getLatestChildReport(childReportDTO);
//                    if (evaluateReport !=null) {
                    generateByEvaluate(courseChild.getChildId(), courseChild.getCenterId(), evaluateReport.getEvaluateNumber(), DateUtils.getNextMonth());
//                    }else {
//                        generateByPromote(courseChild.getChildId(), courseChild.getCenterId(),DateUtils.getNextMonth());
//                    }
                } else {
                    //没测评则按晋级生成训练项目
//                  generateByPromote(courseChild.getChildId(), courseChild.getCenterId());

                    //生成新生标准计划
                    if (childTrainingProgramDTO.getProjectType() == 1) {
                        dealProgram(childTrainingProgramDTO, NewChildProgramConstant.sportOne, 3);
                        dealProgram(childTrainingProgramDTO, NewChildProgramConstant.sportTwo, 4);
                        dealProgram(childTrainingProgramDTO, NewChildProgramConstant.sportThree, 5);
                    }
                    if (childTrainingProgramDTO.getProjectType() == 2) {
                        dealProgram(childTrainingProgramDTO, NewChildProgramConstant.knowledgeOne, 3);
                        dealProgram(childTrainingProgramDTO, NewChildProgramConstant.knowledgeTwo, 4);
                        dealProgram(childTrainingProgramDTO, NewChildProgramConstant.knowledgeThree, 5);
                    }
                    if (childTrainingProgramDTO.getProjectType() == 3) {
                        dealProgram(childTrainingProgramDTO, NewChildProgramConstant.languageOne, 3);
                        dealProgram(childTrainingProgramDTO, NewChildProgramConstant.languageTwo, 4);
                        dealProgram(childTrainingProgramDTO, NewChildProgramConstant.languageThree, 5);
                    }
                    log.error("没有测评记录");
                }
            }
        }
    }

    private void dealProgram(ChildTrainingProgramDTO childTrainingProgramDTO, List<String> list, Integer trainingPlan) {
        int i = 1;
        for (String s : list) {
            ChildTrainingProgram program = new ChildTrainingProgram();
            program.setCenterId(childTrainingProgramDTO.getCenterId());
            program.setChildId(childTrainingProgramDTO.getChildId());
            program.setTrainingProgramNumber(childTrainingProgramDTO.getTrainingProgramNumber());
            program.setProjectType(childTrainingProgramDTO.getProjectType());
            program.setTrainingType(3);
            program.setTrainingPlan(trainingPlan * 10);
            program.setTrainingModule(trainingPlan * 10);
            if (childTrainingProgramDTO.getProjectType().equals(1) && trainingPlan.equals(4) && i <= 7) {
                program.setTrainingPlan(41);
            }
            if (childTrainingProgramDTO.getProjectType().equals(1) && trainingPlan.equals(4) && i > 7) {
                program.setTrainingPlan(42);
            }
            i++;
            program.setTrainingContent(s);
            program.setCreateTime(new Date());
            program.setStatus(0);
            this.childTrainingProgramMapper.insert(program);
        }
    }

    @Override
    @Transactional
    public void saveCourse() {
        log.error("定时任务：月末排下月课");
        String dayDateStart = DateUtils.getMonthBegin(DateUtils.getStrTime(DateUtils.getNextMonth()));
        String dayDateEnd = DateUtils.getMonthEnd(DateUtils.getStrTime(DateUtils.getNextMonth()));
        saveCourseByTime(dayDateStart, dayDateEnd);
    }

    @Override
    public void saveCourseCurMonth() {
        log.error("定时任务：排当月课");
        String dayDateStart = DateUtils.getMonthBegin(DateUtils.getStrTime(DateUtils.getDateYYYYMM()));
        String dayDateEnd = DateUtils.getMonthEnd(DateUtils.getStrTime(DateUtils.getDateYYYYMM()));
        saveCourseByTime(dayDateStart, dayDateEnd);
    }

    @Override
    public void dealPreviewProgram() {
        log.error("定时任务：每月1号将3个月内的未确认的预览项目改为当月");
        //获取3个月内有效的预览项目
        List<String> list = this.childTrainingProgramMapper.selectPreviewProgram(DateUtils.getDateYYYYMM(),90);
        if(!CollectionUtils.isEmpty(list)){
            this.childTrainingProgramMapper.updateTrainingProgramNumber(list,DateUtils.getDateYYYYMM());
        }

    }

    private void saveCourseByTime(String dayDateStart, String dayDateEnd) {
        List<QmsCourseDTO> qmsCourseDTOS = organizationScheduleDetailMapper.listScheduleDetail(dayDateStart.replace("-", ""), dayDateEnd.replace("-", ""));
        if (CollectionUtils.isEmpty(qmsCourseDTOS)) {
            log.error("该时间段课表为空");
            return;
        }
        ChildCourseExample example = new ChildCourseExample();
        example.createCriteria().andDayDateBetween(dayDateStart, dayDateEnd);
        List<ChildCourse> childCourses = childCourseMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(childCourses)) {
            List<QmsCourseDTO> temList = new ArrayList<QmsCourseDTO>();
            temList.addAll(qmsCourseDTOS);

            //排除ChildCourse表里已有的数据
            for (QmsCourseDTO qmsCourseDTO : temList) {
                for (ChildCourse childCourse : childCourses) {
                    if (qmsCourseDTO.getSDId().equals(childCourse.getId())) {
                        //如果有多小孩要先插入然后再移除该课,少的小孩要删除
                        OrganizationScheduleDetailChildExample courseChildExample = new OrganizationScheduleDetailChildExample();
                        courseChildExample.createCriteria().andScheduleDetailIdEqualTo(qmsCourseDTO.getSDId());
                        List<OrganizationScheduleDetailChild> courseChildList = organizationScheduleDetailChildMapper.selectByExample(courseChildExample);

                        //查询已同步该课程下的小孩
                        CourseChildExample ccExample = new CourseChildExample();
                        ccExample.createCriteria().andCourseIdEqualTo(childCourse.getId());
                        List<CourseChild> childList = courseChildMapper.selectByExample(ccExample);

                        if (!CollectionUtils.isEmpty(courseChildList)) {
                            if (CollectionUtils.isEmpty(childList)) {
                                addCourseChild(courseChildList);
                            } else {
                                //多的要插入
                                List<OrganizationScheduleDetailChild> temosdc = new ArrayList<OrganizationScheduleDetailChild>();
                                temosdc.addAll(courseChildList);
                                for (OrganizationScheduleDetailChild organizationScheduleDetailChild : courseChildList) {
                                    for (CourseChild courseChild : childList) {
                                        if (organizationScheduleDetailChild.getChildId().equals(courseChild.getChildId())) {
                                            temosdc.remove(organizationScheduleDetailChild);
                                        }
                                    }
                                }
                                if (!CollectionUtils.isEmpty(temosdc)) {
                                    addCourseChild(temosdc);
                                }

                                //少的要删除(CourseChild表里面多的)
                                List<CourseChild> temCourseChild = new ArrayList<CourseChild>();
                                temCourseChild.addAll(childList);
                                for (CourseChild courseChild : childList) {
                                    for (OrganizationScheduleDetailChild organizationScheduleDetailChild : courseChildList) {
                                        if (courseChild.getChildId().equals(organizationScheduleDetailChild.getChildId())) {
                                            temCourseChild.remove(courseChild);
                                        }
                                    }
                                }
                                if (!CollectionUtils.isEmpty(temCourseChild)) {
                                    delCourseChild(temCourseChild);
                                }
                            }
                        } else {
                            delCourseChild(childList);
                        }
                        qmsCourseDTOS.remove(qmsCourseDTO);
                    }
                }
            }
            List<ChildCourse> temChildCourse = new ArrayList<ChildCourse>();
            temChildCourse.addAll(childCourses);
            //删除课表删除ChildCourse没删除的数据
            for (ChildCourse childCourse : temChildCourse) {
                for (QmsCourseDTO qmsCourseDTO : temList) {
                    if (qmsCourseDTO.getSDId().equals(childCourse.getId())) {
                        childCourses.remove(childCourse);
                    }
                }
            }
            if (!CollectionUtils.isEmpty(childCourses)) {
                List<Long> ids = new ArrayList<Long>();
                for (ChildCourse childCourse : childCourses) {
                    ids.add(childCourse.getId());
                }
                ChildCourseExample childCourseExample = new ChildCourseExample();
                childCourseExample.createCriteria().andIdIn(ids);
                childCourseMapper.deleteByExample(childCourseExample);
            }
        }


        if (CollectionUtils.isEmpty(qmsCourseDTOS)) {
            log.error("没有新增的课程");
            return;
        }

        //查询课程对应的小孩信息
        for (QmsCourseDTO qmsCourseDTO : qmsCourseDTOS) {
            OrganizationScheduleDetailChildExample courseChildExample = new OrganizationScheduleDetailChildExample();
            courseChildExample.createCriteria().andScheduleDetailIdEqualTo(qmsCourseDTO.getSDId());
            List<OrganizationScheduleDetailChild> courseChildList = organizationScheduleDetailChildMapper.selectByExample(courseChildExample);
            if (!CollectionUtils.isEmpty(courseChildList)) {
                List<QmsChildrenDTO> qmsChildrenDTOList = new ArrayList<QmsChildrenDTO>();
                for (OrganizationScheduleDetailChild courseChild : courseChildList) {
                    QmsChildrenDTO qmsChildrenDTO = new QmsChildrenDTO();
                    qmsChildrenDTO.setChildId(courseChild.getChildId());
                    if (courseChild.getChildId() != null) {
                        Child child = iChildService.findById(courseChild.getChildId());
                        if (child != null) {
                            qmsChildrenDTO.setChildName(child.getName());
                        }
                    }

                    qmsChildrenDTOList.add(qmsChildrenDTO);
                }
                qmsCourseDTO.setChildren(qmsChildrenDTOList);
            } else {
                //没有小孩的课程不同步
                continue;
            }

            //插入ChildCourse
            ChildCourse childCourse = new ChildCourse();
            BeanUtils.copyProperties(qmsCourseDTO, childCourse);
            childCourse.setId(qmsCourseDTO.getSDId());
            //qms传过来不一致
            childCourse.setStatus(0);
            Integer courseTypeId = qmsCourseDTO.getCourseTypeId();
            if (courseTypeId == 1) {
                childCourse.setProjectType(2);
            } else if (courseTypeId == 3) {
                childCourse.setProjectType(1);
            } else if (courseTypeId == 5) {
                childCourse.setProjectType(3);
            } else {
                //只同步三门课程
                continue;
            }
            childCourse.setCreateTime(new Date());
            childCourseMapper.insert(childCourse);
            if (!CollectionUtils.isEmpty(qmsCourseDTO.getChildren())) {
                List<QmsChildrenDTO> qmsChildrenDTOS = qmsCourseDTO.getChildren();
                for (QmsChildrenDTO qmsChildrenDTO : qmsChildrenDTOS) {
                    CourseChild courseChild = new CourseChild();
                    BeanUtils.copyProperties(qmsChildrenDTO, courseChild);
                    courseChild.setCourseId(childCourse.getId());
                    courseChild.setConfirm(0);
                    courseChildMapper.insert(courseChild);
                }
            }

        }
    }

    private void addCourseChild(List<OrganizationScheduleDetailChild> organizationScheduleDetailChildList) {
        if (!CollectionUtils.isEmpty(organizationScheduleDetailChildList)) {
            for (OrganizationScheduleDetailChild organizationScheduleDetailChild : organizationScheduleDetailChildList) {
                CourseChild courseChild = new CourseChild();
                courseChild.setCourseId(organizationScheduleDetailChild.getScheduleDetailId());
                courseChild.setConfirm(0);
                courseChild.setChildId(organizationScheduleDetailChild.getChildId());
                if (organizationScheduleDetailChild.getChildId() != null) {
                    Child child = iChildService.findById(organizationScheduleDetailChild.getChildId());
                    if (child != null) {
                        courseChild.setChildName(child.getName());
                    }
                }
                courseChildMapper.insert(courseChild);
            }
        }
    }

    private void delCourseChild(List<CourseChild> courseChildList) {
        if (!CollectionUtils.isEmpty(courseChildList)) {
            List<Long> ids = new ArrayList<Long>();
            for (CourseChild courseChild : courseChildList) {
                ids.add(courseChild.getId());
            }
            CourseChildExample courseChildExample = new CourseChildExample();
            courseChildExample.createCriteria().andIdIn(ids);
            courseChildMapper.deleteByExample(courseChildExample);
        }
    }


    private void generateByEvaluate(Long childId, Long centerId, String evaluateNumber, String trainingProgramNumber) {
        List<TrainingProgram> trainingProgramListA = new ArrayList<TrainingProgram>();
        List<TrainingProgram> trainingProgramListB = new ArrayList<TrainingProgram>();
        int replaceCount = 0;//构音题目需要替换成言语的个数
        //9大训练报告类型
        for (int i = 1; i <= 9; i++) {
            Integer questionCount = getQuestionCount(evaluateNumber, i);
            //获取构音的低于“良好”个数，良好时替换成语言类项目
            if (i == 6) {
                int noGoodCount = evalueRecordService.getCountByProjectModule(evaluateNumber, 5);
                if (noGoodCount < questionCount) {
                    replaceCount = questionCount - noGoodCount;
                    questionCount = noGoodCount;
                }
            }
            if (i == 7 && replaceCount > 0) {
                if (questionCount < 2) {
                    replaceCount = replaceCount - (2 - questionCount);
                    questionCount = questionCount + (2 - questionCount);
                }
            }
            if (i == 8 && replaceCount > 0) {
                questionCount = questionCount + replaceCount;
            }
            if (questionCount == 0) {
                continue;
            }
            List<Long> questionIds = new ArrayList<Long>();
            //查找训练报告类型对应的题目
            List<QuestionReporttype> questionReporttypes = questionReporttypeService.findListByType((short) i);
            if (CollectionUtils.isEmpty(questionReporttypes)) {
                continue;
            }
            for (QuestionReporttype questionReporttype : questionReporttypes) {
                questionIds.add(questionReporttype.getQuestionId());
            }
            //查出学生该报告类型下题目的测评记录
            List<EvaluateRecord> evaluateRecords = evalueRecordService.findByChildEvaluateNumber(childId, evaluateNumber, questionIds);
            if (CollectionUtils.isEmpty(evaluateRecords)) {
                continue;
            }

            //查询学生已稳定的项目
            ChildTrainingProgramExample childTrainingProgramExample = new ChildTrainingProgramExample();
            childTrainingProgramExample.createCriteria().andChildIdEqualTo(childId).andTrainingLevelEqualTo(0).andQuestionIdIn(questionIds);
            List<ChildTrainingProgram> promotedList = childTrainingProgramMapper.selectByExample(childTrainingProgramExample);

            //测评记录去除已稳定的题目
//            if (!CollectionUtils.isEmpty(promotedList)) {
//                List<EvaluateRecord> delRecords = new ArrayList<EvaluateRecord>();
//                delRecords.addAll(evaluateRecords);
//                for (EvaluateRecord evaluateRecord : delRecords) {
//                    for (ChildTrainingProgram childTrainingProgram : promotedList) {
//                        if (evaluateRecord.getQuestionId().equals(childTrainingProgram.getQuestionId()) && evaluateRecord.getChildScore().equals(childTrainingProgram.getTrainingScore())) {
//                            evaluateRecords.remove(evaluateRecord);
//                        }
//                    }
//                }
//
//            }

            //从测评记录中随机抽取取得分最高的questionCount道题,排除题目下挂题目已稳定>70%的题目
            List<EvaluateRecord> selcetList = getEvaluateRecord(evaluateRecords, questionCount* programCount);
            //evaluateRecords剩下的放在selcetList后面，按分值从高到低，防止选中的题目训练项目不够的情况
            evaluateRecords.removeAll(selcetList);
            selcetList.addAll(evaluateRecords);

           /* if(evaluateRecords.size() >= questionCount){
               evaluateRecords = evaluateRecords.subList(0,questionCount);
           }*/
            //从分值高低顺序选PlanA项目
            //当前题目项目不够取测评记录下一题的项目
            int listSize = questionCount * programCount;
            List<TrainingProgram> planA = new ArrayList<TrainingProgram>();
            for (int j = 0; j < selcetList.size(); j++) {
                EvaluateRecord evaluateRecord = selcetList.get(j);
                if (!CollectionUtils.isEmpty(planA) && planA.size() > listSize) {
                    planA = planA.subList(0, listSize);
                    trainingProgramListA.addAll(planA);
                    break;
                } else if (!CollectionUtils.isEmpty(planA) && planA.size() == listSize) {
                    trainingProgramListA.addAll(planA);
                    break;
                }
                List<TrainingProgram> programs = getProgram(childId, evaluateRecord.getQuestionId(), evaluateRecord.getChildScore(), programCount, 1, null, i,promotedList);
                //去除抽到重复的项目
                if (!CollectionUtils.isEmpty(planA)) {
                    for (TrainingProgram trainingProgram : planA) {
                        if (programs.contains(trainingProgram)) {
                            programs.remove(trainingProgram);
                        }
                    }
                }
                planA.addAll(programs);
                //最后一题不管怎样都要加到列表，不会再进入下一个循环，多的要删除
                if (j == selcetList.size() - 1) {
                    if (!CollectionUtils.isEmpty(planA) && planA.size() > listSize) {
                        planA = planA.subList(0, listSize);
                    }
                    trainingProgramListA.addAll(planA);
                }
            }
            //选PlanB项目
            List<TrainingProgram> planB = new ArrayList<TrainingProgram>();
            for (int k = 0; k < selcetList.size(); k++) {
                EvaluateRecord evaluateRecord = selcetList.get(k);
                if (!CollectionUtils.isEmpty(planB) && planB.size() > listSize) {
                    planB = planB.subList(0, listSize);
                    trainingProgramListB.addAll(planB);
                    break;
                } else if (!CollectionUtils.isEmpty(planB) && planB.size() == listSize) {
                    trainingProgramListB.addAll(planB);
                    break;
                }
                List<TrainingProgram> typeBprograms = getProgram(childId, evaluateRecord.getQuestionId(), evaluateRecord.getChildScore(), programCount, 2, trainingProgramListA, i,promotedList);
                //去除抽到重复的项目
                if (!CollectionUtils.isEmpty(planB)) {
                    for (TrainingProgram trainingProgram : planB) {
                        if (typeBprograms.contains(trainingProgram)) {
                            typeBprograms.remove(trainingProgram);
                        }
                    }
                }
                planB.addAll(typeBprograms);
                //最后一题不管怎样都要加到列表，不会再进入下一个循环，多的要删除
                if (k == selcetList.size() - 1) {
                    if (!CollectionUtils.isEmpty(planB) && planB.size() > listSize) {
                        planB = planB.subList(0, listSize);
                    }
                    trainingProgramListB.addAll(planB);
                }
            }
        }
        if (!CollectionUtils.isEmpty(trainingProgramListA)) {
            saveTraninProgram(trainingProgramListA, childId, centerId, trainingProgramNumber);
        }
        if (!CollectionUtils.isEmpty(trainingProgramListB)) {
            saveTraninProgram(trainingProgramListB, childId, centerId, trainingProgramNumber);
        }
        trainingProgramListA.clear();
        trainingProgramListB.clear();


    }

    //随机抽取题目
    private List<EvaluateRecord> getEvaluateRecord(List<EvaluateRecord> records, int questionCount) {
        List<EvaluateRecord> evaluateRecords = new ArrayList<EvaluateRecord>();
        List<EvaluateRecord> records4Score = new ArrayList<EvaluateRecord>();
        List<EvaluateRecord> records3Score = new ArrayList<EvaluateRecord>();
        List<EvaluateRecord> records2Score = new ArrayList<EvaluateRecord>();
        List<EvaluateRecord> records1Score = new ArrayList<EvaluateRecord>();
        List<EvaluateRecord> records0Score = new ArrayList<EvaluateRecord>();
        //测评记录按分值不同存放
        for (EvaluateRecord evaluateRecord : records) {
            //判断改维度下题目已稳定项目是否大于70%，大于时向上取一个分数
            if (evaluateRecord.getChildScore() == null) {
                continue;
            }
            //已稳定数目
            int stableCount = this.childTrainingProgramMapper.selectStableCount(evaluateRecord.getChildId(),evaluateRecord.getQuestionId());
            //对应题目、分数下的总题目数
            int totalCount = this.trainingProgramService.subjectCount(getQuestionId(evaluateRecord.getQuestionId()),evaluateRecord.getChildScore());
            if((double)stableCount/totalCount>0.7){
                evaluateRecord.setChildScore(evaluateRecord.getChildScore()>0?(evaluateRecord.getChildScore()-1):0);
            }
            if (evaluateRecord.getChildScore() == 4) {
                records4Score.add(evaluateRecord);
            } else if (evaluateRecord.getChildScore() == 3) {
                records3Score.add(evaluateRecord);
            } else if (evaluateRecord.getChildScore() == 2) {
                records2Score.add(evaluateRecord);
            } else if (evaluateRecord.getChildScore() == 1) {
                records1Score.add(evaluateRecord);
            } else if (evaluateRecord.getChildScore() == 0) {
                records0Score.add(evaluateRecord);
            }
        }

        if (questionCount < records4Score.size()) {
            Collections.shuffle(records4Score);
            for (int i = 0; i < questionCount; i++) {
//                int r = getRandom(records4Score.size());
                evaluateRecords.add(records4Score.get(i));
            }
            return evaluateRecords;
        } else if (questionCount == records4Score.size()) {
            evaluateRecords.addAll(records4Score);
            return evaluateRecords;
        } else if (questionCount > records4Score.size()) {
            evaluateRecords.addAll(records4Score);
            //还剩几题
            int s3 = questionCount - records4Score.size();
            if (s3 < records3Score.size()) {
                Collections.shuffle(records3Score);
                for (int i = 0; i < s3; i++) {
//                    int r = getRandom(s3);
                    evaluateRecords.add(records3Score.get(i));
                }
                return evaluateRecords;
            } else if (s3 == records3Score.size()) {
                evaluateRecords.addAll(records3Score);
                return evaluateRecords;
            } else if (s3 > records3Score.size()) {
                evaluateRecords.addAll(records3Score);
                //还剩几题
                int s2 = (questionCount - records4Score.size()) - records3Score.size();
                if (s2 < records2Score.size()) {
                    Collections.shuffle(records2Score);
                    for (int i = 0; i < s2; i++) {
//                        int r = getRandom(s2);
                        evaluateRecords.add(records2Score.get(i));
                    }
                    return evaluateRecords;
                } else if (s2 == records2Score.size()) {
                    evaluateRecords.addAll(records2Score);
                    return evaluateRecords;
                } else if (s2 > records2Score.size()) {
                    evaluateRecords.addAll(records2Score);
                    //还剩几题
                    int s1 = ((questionCount - records4Score.size()) - records3Score.size()) - records2Score.size();
                    if (s1 < records1Score.size()) {
                        Collections.shuffle(records1Score);
                        for (int i = 0; i < s1; i++) {
//                            int r = getRandom(s1);
                            evaluateRecords.add(records1Score.get(i));
                        }
                        return evaluateRecords;
                    } else if (s1 == records1Score.size()) {
                        evaluateRecords.addAll(records1Score);
                        return evaluateRecords;
                    } else if (s1 > records1Score.size()) {
                        evaluateRecords.addAll(records1Score);
                        //还剩几题
                        int s0 = (((questionCount - records4Score.size()) - records3Score.size()) - records2Score.size()) - records1Score.size();
                        if (s0 < records0Score.size()) {
                            Collections.shuffle(records0Score);
                            for (int i = 0; i < s0; i++) {
//                                int r = getRandom(s0);
                                evaluateRecords.add(records0Score.get(i));
                            }
                            return evaluateRecords;
                        } else if (s1 == records0Score.size()) {
                            evaluateRecords.addAll(records0Score);
                            return evaluateRecords;
                        }
                    }
                }
            }

        }

        return evaluateRecords;
    }


    //n=10,则随机抽取0-9
    private int getRandom(int n) {
        return (int) (Math.random() * n);
    }

    //1.查出本月做的训练项目来自哪些题目。
    //2.查出这些题目下有训练项目的各分值。
    //3.查询各分值下总的训练项目及晋级的训练项目。
    //4.通过比例挑选该题目下的训练项目
    private void generateByPromote(Long childId, Long centerId, String trainingProgramNumber) {
        ChildTrainingProgramDTO childTrainingProgramDTO = new ChildTrainingProgramDTO();
        childTrainingProgramDTO.setCenterId(centerId);
        childTrainingProgramDTO.setChildId(childId);
        childTrainingProgramDTO.setTrainingProgramNumber(DateUtils.getDateYYYYMM());
        //查询本月做的训练项目归属的所有题目
        List<ChildTrainingProgram> questions = childTrainingProgramService.selectQuestion(childTrainingProgramDTO);
        if (CollectionUtils.isEmpty(questions)) {
            return;
        }
        List<TrainingProgram> toatlTrainingProgramListA = new ArrayList<TrainingProgram>();
        List<TrainingProgram> toatlTrainingProgramListB = new ArrayList<TrainingProgram>();
        //查询本月每题每个分值有几个训练项目
        for (ChildTrainingProgram trainingProgram : questions) {
            childTrainingProgramDTO.setQuestionId(trainingProgram.getQuestionId());
            Short trainigType = 0;
            QuestionReporttype questionReporttype = questionReporttypeService.findById(trainingProgram.getQuestionId());
            if (questionReporttype != null) {
                trainigType = questionReporttype.getTrainingModuleType();
            }
            List<TrainingScoreCountVO> trainingScoreCountVOs = childTrainingProgramService.selectTrainingScoreCount(childTrainingProgramDTO);
            if (CollectionUtils.isEmpty(trainingScoreCountVOs)) {
                continue;
            }
            for (TrainingScoreCountVO trainingScoreCountVO : trainingScoreCountVOs) {
                //该题目下该分值所有的项目数
                TrainingProgramListDTO trainingProgramListDTO = new TrainingProgramListDTO();
                trainingProgramListDTO.setQuestionId(trainingProgram.getQuestionId());
                trainingProgramListDTO.setTrainingScore(trainingScoreCountVO.getTrainingScore());
                Integer totalProgram = 0;
                List<TrainingProgram> trainingProgramList = trainingProgramService.findList(trainingProgramListDTO);
                if (!CollectionUtils.isEmpty(trainingProgramList)) {
                    totalProgram = trainingProgramList.size();
                }
                //该题目下该分值小孩晋级的项目
                ChildTrainingProgramDTO childTrainingProgramListDTO = new ChildTrainingProgramDTO();
                childTrainingProgramListDTO.setTrainingProgramNumber(DateUtils.getDateYYYYMM());
                childTrainingProgramListDTO.setQuestionId(trainingProgram.getQuestionId());
                childTrainingProgramListDTO.setCenterId(centerId);
                childTrainingProgramListDTO.setChildId(childId);
                childTrainingProgramListDTO.setTrainingScore(trainingScoreCountVO.getTrainingScore());
                childTrainingProgramListDTO.setTrainingLevel(1);
                List<ChildTrainingProgram> trainingProgramChildRecords = childTrainingProgramService.list(childTrainingProgramListDTO);
                Integer promotedNum = 0;
                if (!CollectionUtils.isEmpty(trainingProgramChildRecords)) {
                    promotedNum = trainingProgramChildRecords.size();
                }
                //上个月该分值取了几题
                Integer generateCount = trainingScoreCountVO.getScoreCount();
                if (totalProgram != 0) {
                    double rate = promotedNum / totalProgram;
                    if (rate >= 0 && rate < 0.4) {
                        List<TrainingProgram> programs = getByQuestionIdScoreCount(childId, trainingProgram.getQuestionId(), trainingScoreCountVO.getTrainingScore(), generateCount, 1, trainingProgram.getTrainingModule());
                        if (!CollectionUtils.isEmpty(programs)) {
                            toatlTrainingProgramListA.addAll(programs);
                        }
                        List<TrainingProgram> programsB = getByQuestionIdScoreCount(childId, trainingProgram.getQuestionId(), trainingScoreCountVO.getTrainingScore(), generateCount, 2, trainingProgram.getTrainingModule());
                        if (!CollectionUtils.isEmpty(programsB)) {
                            toatlTrainingProgramListB.addAll(programsB);
                        }
                    } else if (rate >= 0.4 && rate < 0.7) {
                        List<TrainingProgram> curScore = getByQuestionIdScoreCount(childId, trainingProgram.getQuestionId(), trainingScoreCountVO.getTrainingScore(), generateCount - 1, 1, trainingProgram.getTrainingModule());
                        if (!CollectionUtils.isEmpty(curScore)) {
                            toatlTrainingProgramListA.addAll(curScore);
                        }
                        List<TrainingProgram> nextScore = getByQuestionIdScoreCount(childId, trainingProgram.getQuestionId(), trainingScoreCountVO.getTrainingScore() - 1, 1, 1, trainingProgram.getTrainingModule());
                        if (!CollectionUtils.isEmpty(nextScore)) {
                            toatlTrainingProgramListA.addAll(nextScore);
                        }

                        List<TrainingProgram> curScoreB = getByQuestionIdScoreCount(childId, trainingProgram.getQuestionId(), trainingScoreCountVO.getTrainingScore(), generateCount - 1, 2, trainingProgram.getTrainingModule());
                        if (!CollectionUtils.isEmpty(curScoreB)) {
                            toatlTrainingProgramListB.addAll(curScoreB);
                        }
                        List<TrainingProgram> nextScoreB = getByQuestionIdScoreCount(childId, trainingProgram.getQuestionId(), trainingScoreCountVO.getTrainingScore() - 1, 1, 2, trainingProgram.getTrainingModule());
                        if (!CollectionUtils.isEmpty(nextScoreB)) {
                            toatlTrainingProgramListB.addAll(nextScoreB);
                        }
                    } else if (rate >= 0.7) {
                        List<TrainingProgram> nextScore = getByQuestionIdScoreCount(childId, trainingProgram.getQuestionId(), trainingScoreCountVO.getTrainingScore() - 1, generateCount, 1, trainingProgram.getTrainingModule());
                        if (!CollectionUtils.isEmpty(nextScore)) {
                            toatlTrainingProgramListA.addAll(nextScore);
                        }

                        List<TrainingProgram> nextScoreB = getByQuestionIdScoreCount(childId, trainingProgram.getQuestionId(), trainingScoreCountVO.getTrainingScore() - 1, generateCount, 2, trainingProgram.getTrainingModule());
                        if (!CollectionUtils.isEmpty(nextScoreB)) {
                            toatlTrainingProgramListB.addAll(nextScoreB);
                        }
                    }
                } else {
                    List<TrainingProgram> programs = getByQuestionIdScoreCount(childId, trainingProgram.getQuestionId(), trainingScoreCountVO.getTrainingScore(), generateCount, 1, trainingProgram.getTrainingModule());
                    if (!CollectionUtils.isEmpty(programs)) {
                        toatlTrainingProgramListA.addAll(programs);
                    }
                    List<TrainingProgram> programsB = getByQuestionIdScoreCount(childId, trainingProgram.getQuestionId(), trainingScoreCountVO.getTrainingScore(), generateCount, 2, trainingProgram.getTrainingModule());
                    if (!CollectionUtils.isEmpty(programsB)) {
                        toatlTrainingProgramListB.addAll(programsB);
                    }
                }

            }
            if (!CollectionUtils.isEmpty(toatlTrainingProgramListA)) {
                saveTraninProgram(toatlTrainingProgramListA, childId, centerId, trainingProgramNumber);
            }
            if (!CollectionUtils.isEmpty(toatlTrainingProgramListB)) {
                saveTraninProgram(toatlTrainingProgramListB, childId, centerId, trainingProgramNumber);
            }

        }

    }


    //挑选训练项目
    private List<TrainingProgram> getByQuestionIdScoreCount(Long childId, Long questionId, Integer score, Integer programCount, Integer typeAB, Integer trainingModule) {
        List<TrainingProgram> trainingProgramList = new ArrayList<TrainingProgram>();
        Integer curScore = score;
        while (curScore != null && curScore >= 0) {
            ChildTrainingProgramExample childTrainingProgramExample = new ChildTrainingProgramExample();
            childTrainingProgramExample.createCriteria().andChildIdEqualTo(childId).andTrainingLevelEqualTo(1).andQuestionIdEqualTo(questionId).andTrainingScoreEqualTo(score);
            List<ChildTrainingProgram> promotedList = childTrainingProgramMapper.selectByExample(childTrainingProgramExample);
            TrainingProgramListDTO trainingProgramListDTO = new TrainingProgramListDTO();
            //多个题目共用训练项目的情况
            trainingProgramListDTO.setQuestionId(getQuestionId(questionId));
            trainingProgramListDTO.setTrainingScore(curScore);
            List<TrainingProgram> programs = trainingProgramService.findList(trainingProgramListDTO);
            if (!CollectionUtils.isEmpty(programs)) {
                //去除已稳定的项目
                if (!CollectionUtils.isEmpty(promotedList)) {
                    List<TrainingProgram> temPrograms = new ArrayList<TrainingProgram>();
                    temPrograms.addAll(programs);
                    for (TrainingProgram trainingProgram : temPrograms) {
                        for (ChildTrainingProgram childTrainingProgram : promotedList) {
                            if (trainingProgram.getId() != null && childTrainingProgram.getTrainingProgramId() != null) {
                                if (trainingProgram.getId().equals(childTrainingProgram.getTrainingProgramId())) {
                                    temPrograms.remove(trainingProgram);
                                }
                            }
                        }
                    }
                }
                trainingProgramList.addAll(programs);
            }
            if (trainingProgramList.size() >= programCount) {
                if (trainingProgramList.size() > programCount) {
                    List<TrainingProgram> curList = trainingProgramList.subList(0, programCount);
                    dealList(curList, questionId, typeAB, trainingModule);
                    return curList;
                }
                dealList(trainingProgramList, questionId, typeAB, trainingModule);
                return trainingProgramList;
            } else {
                curScore--;
            }
        }
        dealList(trainingProgramList, questionId, typeAB, trainingModule);
        return trainingProgramList;
    }

    private void dealList(List<TrainingProgram> trainingProgramList, Long questionId, Integer typeAB, Integer trainingModule) {
        if (!CollectionUtils.isEmpty(trainingProgramList)) {
            for (TrainingProgram trainingProgram : trainingProgramList) {
                trainingProgram.setTypeAB(typeAB);
                //设置回原来的题目ID
                //多个题目共用训练项目的情况
                trainingProgram.setQuestionId(questionId);
                trainingProgram.setTrainingModule(trainingModule);
            }
        }
    }

    //挑选训练项目PlanB
    private List<TrainingProgram> getPlanB(Long childId, Long questionId, Integer score, Integer programCount, Integer typeAB, List<TrainingProgram> planA, Integer trainingModule) {
        List<TrainingProgram> trainingProgramList = new ArrayList<TrainingProgram>();
        ChildTrainingProgramExample childTrainingProgramExample = new ChildTrainingProgramExample();
        childTrainingProgramExample.createCriteria().andChildIdEqualTo(childId).andTrainingLevelEqualTo(0);
        List<ChildTrainingProgram> promotedList = childTrainingProgramMapper.selectByExample(childTrainingProgramExample);

        TrainingProgramListDTO trainingProgramListDTO = new TrainingProgramListDTO();
        //多个题目共用训练项目的情况
        trainingProgramListDTO.setQuestionId(getQuestionId(questionId));
        trainingProgramListDTO.setTrainingScore(score);
        List<TrainingProgram> programs = trainingProgramService.findList(trainingProgramListDTO);

        Integer promoted = isPromoted(promotedList, programs);
        if (promoted == 0) {
            trainingProgramList.addAll(getProgram(childId, questionId, score, programCount, typeAB, planA, trainingModule,promotedList));
        } else if (promoted == 1) {
            trainingProgramList.addAll(getProgram(childId, questionId, score, programCount - 1, typeAB, planA, trainingModule,promotedList));
            trainingProgramList.addAll(getProgram(childId, questionId, score - 1, 1, typeAB, planA, trainingModule,promotedList));
        }

        return trainingProgramList;
    }


    private List<TrainingProgram> getProgram(Long childId, Long questionId, Integer score, Integer programCount, Integer typeAB, List<TrainingProgram> planA, Integer trainingModule,List<ChildTrainingProgram> promotedList) {
        List<TrainingProgram> trainingProgramList = new ArrayList<TrainingProgram>();
        Integer curScore = score;
//        while (curScore >= 0) {
//            ChildTrainingProgramExample childTrainingProgramExample = new ChildTrainingProgramExample();
//            childTrainingProgramExample.createCriteria().andChildIdEqualTo(childId).andTrainingLevelEqualTo(0);
//            List<ChildTrainingProgram> promotedList = childTrainingProgramMapper.selectByExample(childTrainingProgramExample);

            TrainingProgramListDTO trainingProgramListDTO = new TrainingProgramListDTO();
            //多个题目共用训练项目的情况
            trainingProgramListDTO.setQuestionId(getQuestionId(questionId));
            trainingProgramListDTO.setTrainingScore(curScore);
            List<TrainingProgram> programs = trainingProgramService.findList(trainingProgramListDTO);
            Collections.shuffle(programs);
//            Integer promoted = isPromoted(promotedList, programs);
            //0.programs就是要查的列表 1.programs是其中原分值的列表，再加上分值减1的列表 2.programs清空需加上分值减1的列表
//            if (promoted == 1) {
//                programs.addAll(getProgram(childId, questionId, score - 1, 1, typeAB, planA, trainingModule));
//            } else if (promoted == 2) {
//                programs.clear();
//                programs.addAll(getProgram(childId, questionId, score - 1, programCount, typeAB, planA, trainingModule));
//            }

            if (!CollectionUtils.isEmpty(programs)) {
                //去除planA的项目
                if (!CollectionUtils.isEmpty(planA)) {
                    programs.removeAll(planA);
                }
                if (!CollectionUtils.isEmpty(programs)) {
                    //去除已稳定的项目
                    if (!CollectionUtils.isEmpty(promotedList)) {
                        List<TrainingProgram> temPrograms = new ArrayList<TrainingProgram>();
                        temPrograms.addAll(programs);
                        for (TrainingProgram trainingProgram : temPrograms) {
                            for (ChildTrainingProgram childTrainingProgram : promotedList) {
                                if (trainingProgram.getId() != null && childTrainingProgram.getTrainingProgramId() != null) {
                                    if (trainingProgram.getId().equals(childTrainingProgram.getTrainingProgramId())) {
                                        programs.remove(trainingProgram);
                                    }
                                }
                            }
                        }
                    }
                }
                //去除抽到重复的项目
                if (!CollectionUtils.isEmpty(trainingProgramList)) {
                    for (TrainingProgram trainingProgram : trainingProgramList) {
                        if (programs.contains(trainingProgram)) {
                            programs.remove(trainingProgram);
                        }
                    }
                }
                trainingProgramList.addAll(programs);
            }
            if (trainingProgramList.size() >= programCount) {
                if (trainingProgramList.size() > programCount) {
                    List<TrainingProgram> curList = trainingProgramList.subList(0, programCount);
                    dealList(curList, questionId, typeAB, trainingModule);
                    return curList;
                }
                dealList(trainingProgramList, questionId, typeAB, trainingModule);
                return trainingProgramList;
            }
//            else {
//                curScore--;
//            }
//        }
        dealList(trainingProgramList, questionId, typeAB, trainingModule);
        return trainingProgramList;
    }

    //判断该题目该分值是否已经晋级
    private Integer isPromoted(List<ChildTrainingProgram> promotedList, List<TrainingProgram> programs) {
        if (CollectionUtils.isEmpty(promotedList)) {
            return 0;
        }
        if (CollectionUtils.isEmpty(programs)) {
            return 0;
        }
        DecimalFormat df = new DecimalFormat("0.00");
        String data = df.format((double) promotedList.size() / programs.size());
        if (StringUtils.isEmpty(data)) {
            return 0;
        }
        Double rate = Double.parseDouble(data);
        if (rate < 0.4) {
            return 0;
        } else if (rate >= 0.4 && rate <= 0.69) {
            return 1;
        } else if (rate >= 0.7) {
            return 2;
        }
        return 0;
    }

    //多个题目共用一套项目的情况
    private Long getQuestionId(Long questionId) {
        Long returnId = questionId;
        if (questionId == 5) {
            returnId = 4L;
        } else if (questionId == 9) {
            returnId = 8L;
        } else if (questionId == 12) {
            returnId = 11L;
        } else if (questionId == 14) {
            returnId = 13L;
        } else if (questionId == 16) {
            returnId = 15L;
        } else if (questionId == 18) {
            returnId = 17L;
        } else if (questionId == 20) {
            returnId = 19L;
        }
        return returnId;
    }


    private void saveTraninProgram(List<TrainingProgram> trainingPrograms, Long childId, Long centerId, String trainingProgramNumber) {
        for (int i = 0; i < trainingPrograms.size(); i++) {
            insert(trainingPrograms.get(i), childId, centerId, i, trainingProgramNumber);
        }
    }

    private void insert(TrainingProgram trainingProgram, Long childId, Long centerId, Integer num, String trainingProgramNumber) {
        ChildTrainingProgram childTrainingProgram = new ChildTrainingProgram();
        childTrainingProgram.setCenterId(centerId);
        childTrainingProgram.setChildId(childId);
        childTrainingProgram.setTrainingProgramNumber(trainingProgramNumber);
        childTrainingProgram.setProjectType(trainingProgram.getProjectType());
        childTrainingProgram.setInputType(trainingProgram.getInputType());
        childTrainingProgram.setProjectModule(trainingProgram.getProjectModule());
        childTrainingProgram.setQuestionId(trainingProgram.getQuestionId());
        childTrainingProgram.setTrainingScore(trainingProgram.getTrainingScore());
        childTrainingProgram.setTrainingModule(trainingProgram.getTrainingModule());
        childTrainingProgram.setTrainingProgramId(trainingProgram.getId());
        childTrainingProgram.setTrainingPlan(trainingProgram.getTypeAB());
        childTrainingProgram.setTrainingType(1);
        childTrainingProgram.setTrainingNum((num + 1) + "");
        childTrainingProgram.setStatus(0);
        //判断该小孩该项目是否已稳定
        ChildTrainingProgramExample childTrainingProgramExample = new ChildTrainingProgramExample();
        childTrainingProgramExample.createCriteria().andChildIdEqualTo(childId).andTrainingLevelEqualTo(1).andTrainingProgramIdEqualTo(trainingProgram.getId());
        List<ChildTrainingProgram> promotedList = childTrainingProgramMapper.selectByExample(childTrainingProgramExample);
        if (!CollectionUtils.isEmpty(promotedList)) {
            childTrainingProgram.setTrainingLevel(0);
        }
        childTrainingProgram.setTrainingName(trainingProgram.getTrainingName());
        childTrainingProgram.setTrainingContent(trainingProgram.getTrainingContent());
        childTrainingProgram.setModifyDirection(trainingProgram.getModifyDirection());
        childTrainingProgram.setModifyContent(trainingProgram.getModifyContent());
        childTrainingProgram.setCreateTime(new Date());
        childTrainingProgramService.insert(childTrainingProgram);
    }

    //言语级别
    private Short getLanGrade(String evaluateNumber) {
        List<ReportScoreDTO> reportScoreDTOS = evaluateReportService.listProjectModuleScore(evaluateNumber);
        if (CollectionUtils.isEmpty(reportScoreDTOS)) {
            return 0;
        }
        Double gradeScore = 0d;
        DecimalFormat df = new DecimalFormat("0.00");
        for (ReportScoreDTO reportScoreDTO : reportScoreDTOS) {
            double weigh = 0d;
            if (reportScoreDTO.getProjectModule() == 1) {//感知觉
                weigh = 0.055;
            } else if (reportScoreDTO.getProjectModule() == 2) {//运动
                weigh = 0.105;
            } else if (reportScoreDTO.getProjectModule() == 3) {//认知
                weigh = 0.12;
            } else if (reportScoreDTO.getProjectModule() == 4) {//语言
                weigh = 0.17;
            } else if (reportScoreDTO.getProjectModule() == 5) {//构音
                weigh = 0.055;
            } else if (reportScoreDTO.getProjectModule() == 6) {//社交
                weigh = 0.25;
            } else if (reportScoreDTO.getProjectModule() == 7) {//情绪
                weigh = 0.125;
            } else if (reportScoreDTO.getProjectModule() == 8) {//行为
                weigh = 0.12;
            }
            if (reportScoreDTO.getScore() != null && reportScoreDTO.getTotalScore() != null) {
                String data = df.format((double) reportScoreDTO.getScore() / reportScoreDTO.getTotalScore());
                gradeScore = gradeScore + (Double.parseDouble(data) * 100 * weigh);
            }
        }
        if (gradeScore > 59 && gradeScore <= 100) {
            return 0;
        } else if (gradeScore > 39 && gradeScore <= 59) {
            return 1;
        } else if (gradeScore >= 0 && gradeScore <= 39) {
            return 2;
        }
        return 0;
    }


    private Integer getQuestionCount(String evaluateNumber, Integer i) {
        Integer questionCount = 0;
        if (i == 1) {
            questionCount = 3;
            return questionCount;
        } else if (i == 2) {
            questionCount = 2;
            return questionCount;
        } else if (i == 3) {
            questionCount = 1;
            return questionCount;
        } else if (i == 4) {
            questionCount = 4;
            return questionCount;
        } else if (i == 5) {
            questionCount = 2;
            return questionCount;
        }
        Short grade = getLanGrade(evaluateNumber);
        if (grade == 0) {
            if (i == 6) {
                questionCount = 3;
            } else if (i == 7) {
                questionCount = 0;
            } else if (i == 8) {
                questionCount = 1;
            } else if (i == 9) {
                questionCount = 2;
            }
        } else if (grade == 1) {
            if (i == 6) {
                questionCount = 0;
            } else if (i == 7) {
                questionCount = 2;
            } else if (i == 8) {
                questionCount = 2;
            } else if (i == 9) {
                questionCount = 2;
            }
        } else if (grade == 2) {
            if (i == 6) {
                questionCount = 1;
            } else if (i == 7) {
                questionCount = 1;
            } else if (i == 8) {
                questionCount = 2;
            } else if (i == 9) {
                questionCount = 2;
            }
        }

        return questionCount;
    }

}
